package com.mouxidea;

import java.util.*;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailSender {

	private static void send(String content, String subject) {
		Config config =Config.getInstance();
				
        String to = config.getMailTo();
        String from = config.getMailFrom();
        String host = config.getMailHost();

        // Create properties, get Session
        Properties props = new Properties();

        // If using static Transport.send(),
        // need to specify which host to send it to
        props.put("mail.smtp.host", host);
        // To see what is going on behind the scene
        props.put("mail.debug", "true");
        Session session = Session.getInstance(props);

        try {
            // Instantiatee a message
            Message msg = new MimeMessage(session);

            //Set message attributes
            msg.setFrom(new InternetAddress(from));
            InternetAddress[] address = {new InternetAddress(to)};
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject(subject);
            msg.setSentDate(new Date());

            // Set message content
            msg.setText(content);

            //Send the message
            Transport.send(msg);
        }
        catch (MessagingException mex) {
            // Prints all nested (chained) exceptions as well
            mex.printStackTrace();
        }
    }
	
	private static void sendWithSSL(String content, String subject) {
		Config config =Config.getInstance();
				
        final String to = config.getMailTo();
        final String from = config.getMailFrom();
        final String password = config.getMailPassword();
        final String host = config.getMailHost();
        final String port = config.getMailPort();
        final String sslFactory = "javax.net.ssl.SSLSocketFactory";

        // Create properties, get Session
        Properties props = new Properties();

        // If using static Transport.send(),
        // need to specify which host to send it to
        props.put("mail.smtp.host", host);
        // To see what is going on behind the scene
        props.put("mail.debug", "true");
        props.setProperty("mail.smtp.host", host);
        props.setProperty("mail.smtp.socketFactory.class", sslFactory);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", port);
        props.setProperty("mail.smtp.socketFactory.port", port);
        props.put("mail.smtp.auth", "true");
        Session session = Session.getInstance(props,  new Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }});

        try {
            // Instantiatee a message
            Message msg = new MimeMessage(session);

            //Set message attributes
            msg.setFrom(new InternetAddress(from));
            
            List<InternetAddress> addressList = new ArrayList<InternetAddress>();
            if (to != null && !"".equals(to.trim())){
            	String[] toList = to.split(",");
            	
                for (int i=0; i<toList.length; i++){
                	addressList.add(new InternetAddress(toList[i]));
                }
            }
            
            InternetAddress[] address = new InternetAddress[addressList.size()];
            addressList.toArray(address);
            msg.setRecipients(Message.RecipientType.TO, address);
            msg.setSubject(subject);
            msg.setSentDate(new Date());

            // Set message content
            msg.setText(content);

            //Send the message
            Transport.send(msg);
        }
        catch (MessagingException ex) {
            // Prints all nested (chained) exceptions as well
            ex.printStackTrace();
        }
    }
	
	public static void sendAlertEmail(String content, int alarmLevel){
		Config config = Config.getInstance();
//		String content = "This is a test of sending a " +
//                "plain text e-mail through Java.\n" +
//                "Here is line 2.";
		String subject = config.getMailSubject();
		
		switch(alarmLevel){
		case 1:
			subject = "[Critical]"+subject;
			break;
		case 2:
			subject = "[Major]"+subject;
			break;
		case 3:
			subject = "[Minor]"+subject;
			break;
		default:
			break;
		}
		
		if (Config.SECURITY_LEVEL_HIGH.equals(config.getMailSecurityLevel())){
			sendWithSSL(content, subject);
		}
		else {
			send(content, subject);
		}
	}
}
